import random
import pygame

pygame.init()

SCREEN_RECT = pygame.Rect(0,0,480,700)
CLOCK_TIME = 60
TIMER_EVENT = pygame.USEREVENT  # 敌机定时器事件代号
BULLET_EVENT = pygame.USEREVENT + 1 # 子弹定时器

# 精灵类
class Sprite(pygame.sprite.Sprite):

    def __init__(self, image, speed = 1): # image: 精灵图片  speed：运动速度
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.speed = speed

    # 更新图片y轴的坐标
    def update(self): 
        self.rect.y += self.speed 

# 背景类
class Background(Sprite):
    def __init__(self, isFlow = False): # isFlow : 背景图是否超出屏幕
        super().__init__('./飞机大战/images/background.png')
        if isFlow:
            self.rect.y = - self.rect.height  # 如果超出屏幕，则让这张背景放到屏幕上方

    def update(self):
        super().update()
        if self.rect.y > self.rect.height:
            self.rect.y = - self.rect.height

# 敌机类
class Enemy(Sprite):
    def __init__(self):
        super().__init__('./飞机大战/images/enemy1.png')
        self.speed = random.randint(1,3)  # 敌机速度 随机 1~3
        self.rect.bottom = 0    # 设置敌机的y坐标为 -height
        max_x = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(1,max_x)

    def __del__(self):
        print("敌机销毁")

    def update(self):
        super().update()
        if self.rect.y > SCREEN_RECT.height:
            self.kill()

# 子弹类
class Bullet(Sprite):
    def __init__(self):
        super().__init__('./飞机大战/images/bullet1.png',-2)
       
    def update(self):
        super().update()
        if self.rect.y < 0:
            self.kill()
    @staticmethod            
    def __del__():
        print("子弹销毁")

# 英雄类
class Hero(Sprite):
    
    def __init__(self):
        super().__init__('./飞机大战/images/me1.png', 0)
        self.rect.x = SCREEN_RECT.width / 2 - self.rect.width / 2
        self.rect.y = SCREEN_RECT.height - self.rect.bottom - 20
        self.bullets = pygame.sprite.Group() # 子弹精灵

    def update(self):
        self.rect.x += self.speed
        if self.rect.x < 0 :
            self.rect.x = 0
        elif self.rect.right > SCREEN_RECT.width:
            self.rect.x = SCREEN_RECT.width - self.rect.width

    def fill(self):
        bullet = Bullet()
        bullet.rect.bottom = self.rect.y 
        bullet.rect.centerx = self.rect.centerx
        self.bullets.add(bullet)

# 游戏类（主类）
class PlaneGame(object):
    def __init__(self):
        print("游戏初始化")
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        self.clock = pygame.time.Clock()
        pygame.time.set_timer(TIMER_EVENT,1000) # 设置定时器
        pygame.time.set_timer(BULLET_EVENT,500) # 每隔500毫秒执行子弹发射定时器
        self.__create_sprite()  # 创建精灵组
   
    def __create_sprite(self):
        # 创建背景精灵
        bg1 = Background()
        bg2 = Background(True)
        self.bgGroup = pygame.sprite.Group(bg1,bg2)

        # 创建敌机精灵组
        self.enemyGroup = pygame.sprite.Group()

        # 创建英雄精灵
        self.hreo = Hero()
        self.hreoGroup = pygame.sprite.Group(self.hreo)

    def start_game(self):
        print("游戏开始")
        while True:
            self.clock.tick(CLOCK_TIME)
            self.__event_handler()
            self.__update_sprite()
            self.__check_collide()
            pygame.display.update() # 更新视图
    
    # 事件监听
    def __event_handler(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.__game_over()
            elif event.type == TIMER_EVENT:
                self.enemyGroup.add(Enemy())
            elif event.type == BULLET_EVENT:
                self.hreo.fill()

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_RIGHT]:
            self.hreo.speed = 1
        elif keys_pressed[pygame.K_LEFT]:
            self.hreo.speed = -1
        else:
            self.hreo.speed = 0

    # 碰撞检测
    def __check_collide(self): 
        # 子弹消灭敌机
        pygame.sprite.groupcollide(self.hreo.bullets,self.enemyGroup,True,True)
        # 敌机撞毁英雄
        coll_list = pygame.sprite.spritecollide(self.hreo,self.enemyGroup,True)
        if len(coll_list) > 0:
            self.hreo.kill()
            PlaneGame.__game_over()

    # 更新精灵组
    def __update_sprite(self):
        self.bgGroup.update()
        self.bgGroup.draw(self.screen)

        self.enemyGroup.update()
        self.enemyGroup.draw(self.screen)

        self.hreoGroup.update()
        self.hreoGroup.draw(self.screen)

        self.hreo.bullets.update()
        self.hreo.bullets.draw(self.screen)

    @staticmethod
    def __game_over():
        print("游戏结束")
        pygame.quit()
        exit()


if __name__ == "__main__":
    game = PlaneGame()
    game.start_game()
